<template>
    <div class="search-wrap">

        <!-- search box -->
        <div class="search-box shadow-lg">
            <input
                    v-model="search.text"
                    class="search-input"
                    :class="engine.now ? '' : 'no-engine'"
                    type="text"
                    placeholder="搜索内容..."
                    @click.stop.native="searchFocus"
                    @blur="searchBlur"
                    @keyup.enter="keyupEnter"
            >
            <div class="search-engine-wrap no-select">
                <div
                        class="engine-now"
                        @click="search.engine = !search.engine"
                        v-if="engine.now"
                >
                    <img class="engine-img" :src="engine.now.icon"/>
                    <CaretDownOutlined :class="'engine-icon ' + (search.engine ? 'active' : '')"/>
                </div>
                <div class="engine-list-body" v-show="search.engine">
                    <ul class="engine-list shadow">
                        <li
                                class="text-elip"
                                v-for="(item, index) in store.engine"
                                :class="index == engine.idx ? 'active' : ''"
                                @click="engineChange(index)"
                        >
                            <img :src="item.icon" alt=""/>{{item.title}}
                        </li>
                    </ul>
                </div>
            </div>

        </div>

        <!-- history -->
        <div
                class="history-wrap bg-white shadow"
                v-if="store.skin.default.history.state && ((searchPanel.history.length && store.skin.default.history.value == 'on') || searchPanel.bookmark.length)"
                @click.stop.native
        >
            <div class="history-box">
                <span class="his-close" @click="setSearchPanelState(false)">关闭</span>
                <div class="history-body">
                    <div
                            class="his-search"
                            v-if="searchPanel.history.length && store.skin.default.history.value == 'on'"
                    >
                        <div class="his-title">历史搜索</div>
                        <div class="his-body">
                            <div
                                    class="his-items no-select text-elip"
                                    v-for="(item, index) in searchPanel.history"
                                    :key="index"
                                    :title="item.text"
                                    @click="goSearch(index)"
                            >
                                <img :src="item.icon" alt=""/>
                                <span>{{item.text}}</span>
                                <span class="his-items-close" @click.stop="delHistory(index)">x</span>
                            </div>
                        </div>
                    </div>
                    <div class="his-bookmark" v-if="searchPanel.bookmark.length">
                        <div class="his-title">书签</div>
                        <div class="his-body">
                            <div class="his-items no-select text-elip" v-for="(item, index) in searchPanel.bookmark"
                                 :title="item.title" @click="goWebSite(index)">
                                <img :src="item.icon" alt=""/><span>{{item.title}}</span></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import {createVNode} from 'vue';
    import {useStore} from "vuex";
    import website from '/src/config/website';
    import {goUrl, openPage, getArrayStorage, setArrayStorage, removeStorage} from '/src/util/index';
    import {searchBookmark} from '/src/request/api/nav';

    // iconfont
    import {CaretDownOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue';

    export default {
        name: "Search",
        components: {
            CaretDownOutlined,
            ExclamationCircleOutlined,
        },
        data() {
            return {
                // vuex 状态
                store: useStore().state,

                timer: null,
                // 搜索框
                search: {
                    text: '',
                    engine: false,
                },
                // 搜索引擎
                engine: {
                    list: [],
                    idx: 0,
                    now: null,
                },
                // 搜索面板
                searchPanel: {
                    state: false,
                    history: [],
                    bookmark: [],
                    timer: null,
                },
            }
        },
        created() {
            let that = this;
            that.getEngine();
        },
        methods: {
            // engine
            getEngine(refresh = false) {
                let that = this;
                that.$store.dispatch('getEngine', refresh).then(list => {
                    console.log('getEngine', list);
                    let engineNow = website.engineNow,
                        engine = getArrayStorage(engineNow) || false;
                    if (engine) {
                        that.engine.idx = engine.idx;
                        that.engine.now = engine.now;
                    } else {
                        if (list.length) {
                            let now = list[0];
                            setArrayStorage(engineNow, {
                                idx: 0,
                                now: now,
                            });
                            that.engine.now = now;
                        } else {
                            that.engine.now = null;
                            removeStorage(engineNow);
                        }
                    }
                });
            },
            // searchFocus
            searchFocus(e) {
                let that = this;
                that.setSearchPanelState(true);
                that.loadHistory();
                that.search.engine = false;
            },
            // searchBlur
            searchBlur(e) {
                let that = this;
                that.loadHistory();
            },
            // 回车搜索
            keyupEnter() {
                let that = this,
                    token = that.store.token,
                    engine = that.engine.now,
                    text = that.search.text;

                if (!engine) {
                    if (!token) {
                        that.$message.warning('请先登录然后添加一个引擎');
                        return false;
                    }
                    that.$confirm({
                        icon: createVNode(ExclamationCircleOutlined),
                        title: '提醒',
                        content: '您还未准备好一个搜索引擎,是否前往添加?',
                        okText: '是',
                        cancelText: '否',
                        onOk() {
                            goUrl('/user/manage-engine');
                        },
                        onCancel() {
                        },
                    });
                    return false;
                }
                if (!text) {
                    that.$message.warning('输入搜索内容');
                    return false;
                }

                let url = engine.url,
                    data = {
                        id: engine.id,
                        eid: engine.eid,
                        icon: engine.icon,
                        title: engine.title,
                        text: text,
                        url: url + text,
                    };
                // 缓存搜索
                let key = website.question,
                    arr = getArrayStorage(key) || [];
                arr.push(data);
                setArrayStorage(key, arr);
                that.loadHistory();
                that.setSearchPanelState(false);
                // 跳转
                that.$store.dispatch('searchQuestion', {
                    text: data.text,
                    id: data.id,
                    eid: data.eid,
                }).then(res => {
                    that.search.text = '';
                    openPage(data.url, 'search');
                })
            },
            // 引擎切换
            engineChange(index) {
                let that = this,
                    list = that.store.engine,
                    now = list[index];
                setArrayStorage('ENGINENOW', {
                    idx: index || 0,
                    now: now,
                });
                that.engine.idx = index;
                that.engine.now = now;
                that.search.engine = !that.search.engine;
            },
            // 加载历史搜索纪录
            loadHistory() {
                this.searchPanel.history = getArrayStorage(website.question) || [];
            },
            // 搜索书签
            loadBookmark(title) {
                let that = this;
                searchBookmark({
                    title: title,
                }).then(res => {
                    //that.$message.success(res.msg || website.msg.success);
                    that.searchPanel.bookmark = res.list;
                }).catch(err => {
                    that.$message.error(err.msg || website.msg.error);
                });
            },
            // 前往历史搜索
            goSearch(index) {
                let that = this,
                    list = that.searchPanel.history,
                    data = list[index];
                that.setSearchPanelState(false);
                // 跳转
                that.$store.dispatch('searchQuestion', {
                    text: data.text,
                    id: data.id,
                    eid: data.eid,
                }).then(res => {
                    openPage(data.url, 'search');
                })

            },
            // 前往网站
            goWebSite(index) {
                let that = this,
                    list = that.searchPanel.bookmark,
                    data = list[index];
                that.$store.dispatch('clickBookmark', {
                    uwid: data.id,
                    wid: data.wid,
                }).then(res => {
                    that.setSearchPanelState(false);
                    openPage(data.url, 'bookmark');
                })
            },
            // 删除一条历史记录
            delHistory(index) {
                let that = this,
                    list = that.searchPanel.history;
                list.splice(parseInt(index || 0), 1);
                that.searchPanel.history = list;
                setArrayStorage(website.question, list || []);
            },
            // 设置搜索面板状态
            setSearchPanelState(val = true) {
                let that = this,
                    config = that.store.skin.default;
                config.history.state = val;
                that.$store.commit('setNowSkin', config);
                //this.searchPanel.state = val;
            },
            // goUrl
            goUrl(url) {
                goUrl(url);
            },
        },
        watch: {
            // 监听搜索文本
            'search.text'(title) {
                let that = this,
                    timer = that.searchPanel.timer;
                if (timer) {
                    clearTimeout(timer);
                    that.searchPanel.timer = null;
                } else {
                    if (title) {
                        that.searchPanel.timer = setTimeout(() => {
                            that.loadBookmark(title);
                        }, 300);
                    }
                    // 搜索文本为空
                    else {
                        that.searchPanel.bookmark = [];
                        //that.loadBookmark(title);
                    }
                }
            },
            // key 变化
            '$store.state.key'(val) {
                this.getEngine(true);
            },
        }
    }
</script>

<style lang="less" scoped>
    @width: 100%;
    @height: 45px;
    @radius: 10px;
    @radiusMin: 5px;
    @base: #ffffff;
    @active: #454545;
    @bgColor: #efefef;

    .search-wrap {
        width: @width;
        margin: 50px auto 0 0;
        text-align: center;
        position: relative;

        .search-box {
            width: 100%;
            position: relative;
            border-radius: @radius;

            &:after {
                font-size: 12px;
                content: 'Enter';
                color: #777777;
                display: block;
                position: absolute;
                top: 0;
                right: 0;
                bottom: 0;
                padding: 0 10px;
                line-height: @height;
            }

            .search-input {
                color: black;
                width: 100%;
                box-sizing: border-box; //其他浏览器
                -webkit-box-sizing: border-box; //谷歌
                -moz-box-sizing: border-box; //火狐
                height: @height;
                line-height: @height;
                border-radius: @radius;
                border: none;
                padding-right: 50px;
                padding-left: 60px;
                outline: none;
            }

            .no-engine {
                padding-left: 20px;
            }

            .search-engine-wrap {
                position: absolute;
                top: 0;
                left: 0;
                cursor: pointer;

                .engine-now {
                    display: flex;
                    align-items: center;
                    width: 55px;
                    height: 45px;
                    padding: 0 5px 0 15px;
                    border-radius: @radius 0 0 @radius;
                    overflow: hidden;

                    &:hover {
                        background-color: #efefef;
                    }

                    .engine-img {
                        position: relative;
                        width: 22px;
                        height: 22px;

                        &:after {
                            content: '';
                            display: block;
                            width: 100%;
                            height: 100%;
                            position: absolute;
                            z-index: 2;
                            top: 0;
                            left: 0;
                            background: url('/src/assets/imgs/network.png') white;
                            background-size: 100%;
                        }
                    }

                    .engine-icon {
                        font-size: 12px;
                        color: #939393;
                        transition: all .5s;

                        &.active {
                            transform: rotate(180deg);
                            -moz-transform: rotate(180deg); /* Firefox */
                            -webkit-transform: rotate(180deg); /* Safari 和 Chrome */
                            -o-transform: rotate(180deg); /* Opera */
                        }
                    }
                }

                .engine-list-body {
                    position: relative;

                    .engine-list {
                        position: absolute;
                        top: 5px;
                        left: 0;
                        background-color: #ffffff;
                        z-index: 10000;
                        margin: 0;
                        border-radius: @radiusMin;
                        overflow: hidden;
                        max-height: 200px;
                        overflow-y: auto;

                        li {
                            display: flex;
                            align-items: center;
                            text-align: left;
                            padding: 5px 10px;

                            &.active {
                                background-color: #efefef;
                            }

                            img {
                                position: relative;
                                width: 20px;
                                height: 20px;
                                margin-right: 5px;

                                &:after {
                                    content: '';
                                    display: block;
                                    width: 100%;
                                    height: 100%;
                                    position: absolute;
                                    z-index: 2;
                                    top: 0;
                                    left: 0;
                                    background: url('/src/assets/imgs/network.png') white;
                                    background-size: 100%;
                                }
                            }

                            div {
                                font-size: 12px;
                            }
                        }
                    }
                }
            }
        }

        /*.search-engine {
            width: 100%;
            font-size: 0;
            position: absolute;
            top: 45px;
            left: 0;
            z-index: 1000;

            li {
                display: inline-block;
                margin: 20px 10px 0 10px;
                width: 50px;
                padding: 5px 5px;
                border-radius: 25px;
                background-color: @base;
                transition: all .5s;
                cursor: pointer;
                box-shadow: 0 0 10px rgb(200, 200, 200);
                opacity: .9;

                &:hover, &.engine-active {
                    background-color: @active;

                    img {
                        &:after {
                            transition: all .5s;
                            content: '';
                            display: block;
                            width: 100%;
                            height: 100%;
                            position: absolute;
                            z-index: 2;
                            top: 0;
                            left: 0;
                            background: url('/src/assets/imgs/network_white.png') @active;
                            background-size: 100%;
                        }
                    }
                }

                img {
                    display: inline-block;
                    width: 20px;
                    height: 20px;
                    border-radius: 4px;
                    position: relative;

                    &:after {
                        transition: all .5s;
                        content: '';
                        display: block;
                        width: 100%;
                        height: 100%;
                        position: absolute;
                        z-index: 2;
                        top: 0;
                        left: 0;
                        background: url('/src/assets/imgs/network.png') @base;
                        background-size: 100%;
                    }
                }
            }
        }*/

        .history-wrap {
            position: absolute;
            top: 50px;
            left: 0;
            width: 100%;
            min-height: 100px;
            max-height: 300px;
            z-index: 100;
            overflow: hidden;
            border-radius: @radiusMin;

            .history-box {
                overflow-x: hidden;
                overflow-y: auto;
                max-height: 260px;
                position: relative;
                padding: 20px;

                .his-close {
                    position: absolute;
                    top: 20px;
                    right: 20px;
                    font-size: 12px;
                    padding: 5px 8px;
                    background-color: #efefef;
                    border-radius: @radiusMin;
                    cursor: pointer;

                    &:hover {
                        background-color: #dfdfdf;
                    }
                }

                .history-body {
                    border-top: 1px solid transparent;


                    .his-search, .his-bookmark {
                        font-size: 0;
                        text-align: left;
                    }

                    .his-title {
                        margin: 10px 0;
                        font-size: 16px;
                        height: 25px;
                        line-height: 25px;
                    }

                    .his-items {
                        width: 180px;
                        height: 40px;
                        border-radius: 4px 40px 40px 4px;
                        display: inline-block;
                        font-size: 14px;
                        cursor: pointer;
                        padding: 10px 25px 10px 10px;
                        vertical-align: middle;
                        position: relative;

                        &:hover {
                            background-color: @bgColor;

                            .his-items-close {
                                display: inline-block;
                            }

                            img:after {
                                background-color: @bgColor;
                            }
                        }

                        img {
                            display: block;
                            float: left;
                            width: 20px;
                            height: 20px;
                            margin-right: 5px;
                            position: relative;

                            &:after {
                                content: '';
                                display: block;
                                width: 100%;
                                height: 100%;
                                position: absolute;
                                z-index: 2;
                                top: 0;
                                left: 0;
                                background: url('/src/assets/imgs/network.png') white;
                                background-size: 100%;
                            }
                        }

                        span {
                            font-size: 14px;
                        }

                        .his-items-close {
                            display: none;
                            position: absolute;
                            top: 8px;
                            right: 8px;
                            width: 24px;
                            height: 24px;
                            border-radius: @radius;
                            text-align: center;
                            line-height: 24px;
                            transition: .5s;
                            font-size: 14px;

                            &:hover {
                                color: white;
                                background-color: #aaaaaa;
                            }
                        }
                    }

                }
            }
        }
    }

    @media screen and (max-width: @width + 40) {
        .search-wrap {
            width: auto;
        }
    }
</style>
